package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.SearchService;
import com.atguigu.gulimall.search.vo.SearchParamVo;
import com.atguigu.gulimall.search.vo.SearchResultVo;
import jdk.nashorn.internal.objects.NativeUint8Array;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lk
 * @version 1.0.0
 * @Description 检索业务
 * @createTime 2024/1/21 14:13
 */
@Slf4j
@Service(value = "searchService")
public class SearchServiceImpl implements SearchService {

    @Resource
    RestHighLevelClient restHighLevelClient;

    /**
     * 返回检索的结果
     * @param searchParamVo searchParamVo
     * @return
     */
    @Override
    public SearchResultVo search(SearchParamVo searchParamVo) {
        //1.构建请求
        SearchRequest searchRequest = buildSearchRequest(searchParamVo);
        log.info("构建的请求:{}",searchRequest.source().toString());
        //2.执行请求
        SearchResponse searchResponse = null;
        try {
            searchResponse = restHighLevelClient.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //3.封装返回结果
        SearchResultVo searchResultVo = buildSearchResponse(searchResponse,searchParamVo);
        return searchResultVo;
    }

    /**
     * 1.构建请求-模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存），排序，分页，高亮，聚合分析
     * @param searchParamVo searchParamVo
     * @return SearchRequest
     */
    private SearchRequest buildSearchRequest(SearchParamVo searchParamVo) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存）
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //1.检索关键字
        if(!StringUtils.isEmpty(searchParamVo.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",searchParamVo.getKeyword()));
        }
        //2.过滤三级分类
        if(searchParamVo.getCatalog3Id() != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",searchParamVo.getCatalog3Id()));
        }
        //3.过滤是否有库存
        if(searchParamVo.getHasStock() != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock",searchParamVo.getHasStock()==1));
        }
        //4.过滤价格区间：_500/1_500/500_
        if(!StringUtils.isEmpty(searchParamVo.getSkuPrice())){
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String skuPrice = searchParamVo.getSkuPrice();
            String[] price = skuPrice.split("_");
            if(price.length == 2){
                rangeQuery.gte(price[0]).lte(price[1]);
            } else if(price.length == 1) {
                if(skuPrice.startsWith("_")){
                    rangeQuery.lte(price[1]);
                }
                if(skuPrice.endsWith("_")){
                    rangeQuery.gte(price[0]);
                }
            }
            boolQueryBuilder.filter(rangeQuery);
        }
        //5.过滤品牌
        if(searchParamVo.getBrandId() != null){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",searchParamVo.getBrandId()));
        }
        //6.过滤属性
        if(searchParamVo.getAttrs() != null && searchParamVo.getAttrs().size() > 0){
            //attrs=1_5寸:8寸&2_16G:8G
            searchParamVo.getAttrs().forEach(attr->{
                BoolQueryBuilder attrBoolQuery  = QueryBuilders.boolQuery();
                //attrs=1_5寸:8寸
                String[] attrInfo = attr.split("_");
                //6.1、属性id
                attrBoolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrInfo[0]));
                //6.2、属性值
                attrBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrInfo[1].split(":")));
                boolQueryBuilder.filter(QueryBuilders.nestedQuery("attrs",attrBoolQuery, ScoreMode.None));
            });
        }
        //封装所有的查询条件
        searchSourceBuilder.query(boolQueryBuilder);
        /**
         * 排序
         * sort=saleCount_asc/desc
         * sort=skuPrice_asc/desc
         * sort=hotScore_asc/desc
         * 分页
         */
        //7.排序
        if(!StringUtils.isEmpty(searchParamVo.getSort())){
            String[] sortInfo = searchParamVo.getSort().split("_");
             SortOrder order = sortInfo[1].equalsIgnoreCase(SortOrder.ASC.toString())?SortOrder.ASC:SortOrder.DESC;
             searchSourceBuilder.sort(sortInfo[0],order);
        }
        //8.页码
        searchSourceBuilder.from((searchParamVo.getPageNum()-1) * EsConstant.SEARCH_PAGESIZE);
        searchSourceBuilder.size(EsConstant.SEARCH_PAGESIZE);
        //9.高亮
        if(!StringUtils.isEmpty(searchParamVo.getKeyword())){
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            searchSourceBuilder.highlighter(builder);
        }
        //10. 聚合分析
        //10.1、品牌
        //10.1.1 品牌聚合-品牌id
        TermsAggregationBuilder brandIdAgg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        //品牌聚合的子聚合-品牌名-品牌图片
        brandIdAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brandIdAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        searchSourceBuilder.aggregation(brandIdAgg);
        //10.2、分类
        //10.2.1 品牌聚合-分类id-分类名
        TermsAggregationBuilder catalogIdAgg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(50);
        catalogIdAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        searchSourceBuilder.aggregation(catalogIdAgg);
        //10.3、属性
        NestedAggregationBuilder attrsNestedAgg = AggregationBuilders.nested("attr_agg", "attrs");
        //聚合出当前所有的attrId
        TermsAggregationBuilder attrAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(50);
        //聚合分析出当前attrId对应的名字
        attrAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        //聚合分析出当前attrId对应所有可能的属性值attrValue
        attrAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attrsNestedAgg.subAggregation(attrAgg);
        searchSourceBuilder.aggregation(attrsNestedAgg);
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX},searchSourceBuilder);
        return searchRequest;
    }

    /**
     * 3.封装返回结果
     * @param searchResponse searchResponse
     * @return SearchResultVo
     */
    private SearchResultVo buildSearchResponse(SearchResponse searchResponse,SearchParamVo searchParamVo) {
        SearchResultVo searchResultVo = new SearchResultVo();
        SearchHit[] hits = searchResponse.getHits().getHits();
        //1.封装所有商品信息
        List<SkuEsModel> products = new ArrayList<>();
        if(hits != null && hits.length > 0){
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, new TypeReference<SkuEsModel>() {});
                //高亮标题处理
                if(!StringUtils.isEmpty(searchParamVo.getKeyword())){
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(string);
                }
                products.add(skuEsModel);
            }
        }
        searchResultVo.setProducts(products);
        //2、涉及到的所有品牌
        List<SearchResultVo.BrandVo> brands=new ArrayList<>();
        ParsedLongTerms brand_agg = searchResponse.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            //获取品牌信息
            SearchResultVo.BrandVo brandVo = new SearchResultVo.BrandVo();
            //获取品牌的ID
            brandVo.setBrandId(bucket.getKeyAsNumber().longValue());
            //获取品牌名字
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String brandName  = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            //获取品牌图片
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            brands.add(brandVo);
        }
        searchResultVo.setBrands(brands);
        //3.涉及到的所有分类
        List<SearchResultVo.CatalogVo> catalogs=new ArrayList<>();
        ParsedLongTerms catalog_agg = searchResponse.getAggregations().get("catalog_agg");
        for (Terms.Bucket bucket : catalog_agg.getBuckets()) {
            SearchResultVo.CatalogVo catalogVo = new SearchResultVo.CatalogVo();
            //设置分类id
            catalogVo.setCatalogId(bucket.getKeyAsNumber().longValue());
            //设置分类名
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            catalogVo.setCatalogName(catalog_name_agg.getBuckets().get(0).getKeyAsString());
            catalogs.add(catalogVo);
        }
        searchResultVo.setCatalogs(catalogs);
        //4.涉及到的所有属性
        List<SearchResultVo.AttrVo> attrs =new ArrayList<>();
        ParsedNested attr_agg = searchResponse.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResultVo.AttrVo attrVo = new SearchResultVo.AttrVo();
            //设置属性id
            attrVo.setAttrId(bucket.getKeyAsNumber().longValue());
            //设置属性名
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            attrVo.setAttrName(attr_name_agg.getBuckets().get(0).getKeyAsString());
            //设置属性值
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> collect = attr_value_agg.getBuckets().stream().map(item -> item.getKeyAsString()).collect(Collectors.toList());
            attrVo.setAttrValue(collect);
            attrs.add(attrVo);
        }
        //面包屑
        List<SearchResultVo.NavVo> navs=null;
        if(searchParamVo.getAttrs()!=null && searchParamVo.getAttrs().size()>0){
            navs=searchParamVo.getAttrs().stream().map(attr->{
                //attrs=1_2018:2019
                SearchResultVo.NavVo navVo = new SearchResultVo.NavVo();
                String[] str = attr.split("_");
                //1.属性名（在es返回中获取）
                for (Terms.Bucket bucket : attr_id_agg.getBuckets()){
                    if(bucket.getKey().equals(Long.parseLong(str[0]))){
                        ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name_agg");
                        navVo.setNavName(attrNameAgg.getBuckets().get(0).getKeyAsString());
                    }
                }
                //2.属性值
                navVo.setNavValue(str[1]);
                //3.导航链接
                //3.1、获取请求参数
                String encode=null;
                try {
                    encode = URLEncoder.encode(attr, "UTF-8");
                    encode.replace("+","%20");//浏览器与java对空格的编码不一致
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String queryString = searchParamVo.get_queryString();
                //3.2、将当前属性替换为空串
                String replace = queryString.replace("&attrs=" + encode, "");
                navVo.setLink("http://search.bilimall.com/list.html?"+replace);
                return navVo;
            }).collect(Collectors.toList());
        }
        searchResultVo.setNavs(navs);


        searchResultVo.setAttrs(attrs);
        //5.分页信息
        //获取总记录数
        long total = searchResponse.getHits().getTotalHits().value;
        //设置总记录数
        searchResultVo.setTotal(total);
        //设置总页码
        Integer totalPage= (int) (total % EsConstant.SEARCH_PAGESIZE == 0?(total/EsConstant.SEARCH_PAGESIZE):(total/EsConstant.SEARCH_PAGESIZE+1));
        searchResultVo.setTotalPages(totalPage);
        //设置当前页码
        searchResultVo.setPageNum(searchParamVo.getPageNum());
        //设置页码列表
        List<Integer> pageNavs=new ArrayList<>();
        for (int i = 1; i <= totalPage; i++) {
            pageNavs.add(i);
        }
        searchResultVo.setPageNavs(pageNavs);

        return searchResultVo;
    }
}
